package com.littlehu.system.controller;

import com.example.common.BaseDto;
import com.example.common.ResultUtils;
import com.example.common.utils.ApiSendSmsCodeUtils;
import com.littlehu.pojo.UserToken;
import com.littlehu.service.TokenService;
import com.littlehu.system.utils.JwtUtils;
import com.example.common.utils.TextUtils;
import com.littlehu.pojo.User;
import com.littlehu.pojo.Verification;
import com.littlehu.service.UserService;
import com.littlehu.service.VerificationService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @author littlehu
 * @data 2018/6/25 18:28
 * @Email 807115007@qq.com
 **/

@RequestMapping("/user")
@RestController
@EnableTransactionManagement
public class UserController {

    @Autowired
    private VerificationService verificationService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;



    @RequestMapping("/getSmsCode")
    public BaseDto sendSmsCode(@RequestParam("phone") String phone){
        User user = userService.selectUserByPhone(phone);
        if(user != null){
            return ResultUtils.fail(100 , "该手机号已被注册");
        }

        int random = (int)(Math.random()*(9999-1000+1))+1000;
        String code = "#code#=" + random;
        boolean status = ApiSendSmsCodeUtils.getRequest2(phone , URLEncoder.encode(code));
        if(status){
            Verification verification = new Verification();
            verification.setPhone(phone);
            verification.setCode(random + "");
            verification.setCreateDate(new Date());
            verificationService.insertVerCode(verification);
            return ResultUtils.success(null);
        }else{
            return ResultUtils.fail(102 , "短信发送失败");
        }
    }

    @RequestMapping("/register")
    public BaseDto register(@RequestParam("userName") @NotNull String userName , @RequestParam("phone") @NotNull String phone ,@RequestParam("userPassword") @NotNull String password ,  @RequestParam("userSex") @NotNull String userSex , @RequestParam("code") @NotNull String code){
        if(!TextUtils.isMobileNO(phone)){
            return ResultUtils.fail( 103 , "手机格式不正确");
        }

        User temuser = userService.selectUserByPhone(phone);
        if(temuser != null){
            return ResultUtils.fail(100 , "该手机号已被注册");
        }


        List<Verification> verificationCodes = verificationService.selectByPhones(phone);

        if(verificationCodes == null || verificationCodes.size() == 0){
            return ResultUtils.fail(103 , "请发送验证码");
        }

        if(!StringUtils.equals(verificationCodes.get(0).getCode() , code)){
            return ResultUtils.fail(103 , "短信验证码错误");
        }

        if(new Date().getTime() - verificationCodes.get(0).getCreateDate().getTime() > 90 * 1000){
            return ResultUtils.fail(103 , "验证码已失效");
        }

        User user = new User();
        user.setUserName(userName);
        user.setUserPhone(phone);
        user.setUserSex(userSex);
        user.setUserPassword(DigestUtils.sha256Hex(password));
        user.setUserJoinDate(new Date());

        userService.insertUser(user);
        return ResultUtils.success(null);

    }

    @RequestMapping("/getAllUser")
    public BaseDto<List<User>> getAllUser(){
        return ResultUtils.success(userService.selectAllUser());
    }

    @RequestMapping("/login")
    public BaseDto login(HttpServletResponse response ,@RequestParam("userPhone") String userPhone , @RequestParam("userPassword") String userpassword){
        User user = userService.selectUserByPhone(userPhone);
        if(user == null){
            return ResultUtils.fail(103, "该账号尚未注册");
        }
        if(!StringUtils.equals(user.getUserPassword() , DigestUtils.sha256Hex(userpassword))){
            return ResultUtils.fail(103, "密码不匹配");
        }
        String token = jwtUtils.generateToken(user.getId());

        UserToken userToken = tokenService.selectUserTokenById(user.getId());
        if(userToken == null){
            userToken = new UserToken();
            userToken.setToken(token);
            userToken.setUserId(user.getId());
            Date nowDate = new Date();
            userToken.setUpdateTime(nowDate);
            userToken.setExpireTime(new Date(nowDate.getTime() + jwtUtils.getExpire() * 1000));
            tokenService.insertUserToken(userToken);
        }else{
            userToken.setToken(token);
            Date nowDate = new Date();
            userToken.setUpdateTime(nowDate);
            userToken.setExpireTime(new Date(nowDate.getTime() + jwtUtils.getExpire() * 1000));
            tokenService.updateUserToken(userToken);
        }
        Cookie cookie = new Cookie("author" , token);
        response.addCookie(cookie);
        return ResultUtils.success(user);
    }


}
